package hz.mobileproject.pda.ui.activity;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIItemListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cn.droidlover.xdroidmvp.mvp.XActivity;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.request.Request_insert_odd_post;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.EventLoadFaultCategory;
import hz.mobileproject.pda.entity.response.EventReportTypeBean;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.presenter.PAddOddPost;
import hz.mobileproject.pda.tree.FileBean;
import hz.mobileproject.pda.tree.Node;
import hz.mobileproject.pda.tree.SimpleTreeAdapter;
import hz.mobileproject.pda.tree.TreeListViewAdapter;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;

import static com.google.zxing.activity.CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN;

/**
 * 添加零星报备界面
 */
public class AddOddPostActivity extends XActivity<PAddOddPost> implements IShowBarcodeStr {

    private TagFlowLayout flowlayout_post_type;

    private Gson gson;
    private LayoutInflater mInflater;
    private String[] mVals;
    //返回上报类型的集合
    private List<EventReportTypeBean> mEventReportTypeBeanList;
    private List<String> EventReportTypeBeanStrings = new ArrayList<>();
    private LinearLayout ll_gzlb_and_clbm;
    private int index_choose_report_type = -1;

    private EditText et_title;
    private EditText et_content;
    private Button bt_commit;
    private String et_title_string;
    private String et_content_string;

    //故障类别
    private List<EventLoadFaultCategory> mEventLoadFaultCategories;
    private List<String> loadFaultCategorys = new ArrayList<>();
    private String[] mVals2;
    private TagFlowLayout flowlayout_guzhang_leibie;
    private int index_choose_guzhang_leibie = -1;

    private List<FileBean> mDatas;
    private ListView mTree;
    @SuppressWarnings("rawtypes")
    private TreeListViewAdapter mAdapter;
    private SPUtils spUtils;
    private Request_insert_odd_post mRequest_insert_odd_post;
    private String mReport_type;
    private String mFalutGenreId;

    //后添加扫描民警功能
    private TextView tv_policeName;
    private TextView tv_policeID;
    private HandleBroadcast handleBroadcast;
    private SoundPool soundpool;
    private int soundid;
    private LoadingDialog loadingDialog;
    private boolean on_Off = true;
    private String mCusnumber;
    private String policeCode;

    //后添加选择 的TextView显示
    private TextView tv_post_type;
    private TextView tv_guzhang_leibie;
    private TextView tv_chuli_bumen;

    //扫描获取的民警信息
    private String police_name;
    private String police_id;
    private String department_id;
    private String department_name;
    private String mNodeDeptName;
    private ViewGroup.LayoutParams mParams;

    //9月8日修改样式
    private EditText et_post_type;

    private static final int REQUEST_CODE_POLICE = 1021;
    public static final int RESULT_CODE_QR_SCAN = 0xA1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onWidgetClick(View view) {

    }

    //扫描回调
    @Override
    public void updateText(String msg) {
        soundpool.play(soundid, 1, 1, 0, 0, 1);
        boolean status = msg.contains("P");
        if (status){
            if(on_Off) {
                policeCode = msg.substring(1);
                Request_loadPoliceInfo loadPoliceInfo = new Request_loadPoliceInfo();
                loadPoliceInfo.setCusNumber(mCusnumber);
                loadPoliceInfo.setPoliceCode(policeCode);
                getP().setData(gson.toJson(loadPoliceInfo), 10);   //获取民警信息
                on_Off = false;
            }

        }


    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initScan();
        //开启对话框
//        showPromptDlg();
        spUtils = SPUtils.getInstance("app_login");
        bt_commit = (Button) findViewById(R.id.bt_commit);
        gson = new Gson();
        mInflater = LayoutInflater.from(this);
        getP().setData("",1);
        ll_gzlb_and_clbm = (LinearLayout) findViewById(R.id.ll_gzlb_and_clbm);
        flowlayout_guzhang_leibie = (TagFlowLayout) findViewById(R.id.flowlayout_guzhang_leibie);
        flowlayout_post_type = (TagFlowLayout) findViewById(R.id.flowlayout_post_type);
        mTree = (ListView) findViewById(R.id.listview);
        et_title = (EditText) findViewById(R.id.et_title);
        et_content = (EditText) findViewById(R.id.et_content);
        tv_policeName = (TextView) findViewById(R.id.tv_policeName);
        tv_policeID = (TextView) findViewById(R.id.tv_policeID);
        tv_post_type = (TextView) findViewById(R.id.tv_post_type);
        tv_guzhang_leibie = (TextView) findViewById(R.id.tv_guzhang_leibie);
        tv_chuli_bumen = (TextView) findViewById(R.id.tv_chuli_bumen);

        //TODO 9月8日
        et_post_type = (EditText) findViewById(R.id.et_post_type);

        //请求故障类别
        getP().setData("",2);

        //加载部门
        getP().setData("",3);

        mRequest_insert_odd_post = new Request_insert_odd_post();
        mCusnumber = spUtils.getString("cusnumber");
        mRequest_insert_odd_post.setCus_number(mCusnumber);



        bt_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_title_string = et_title.getText().toString().trim();
                et_content_string = et_content.getText().toString().trim();
                //提交标题和内容
                mRequest_insert_odd_post.setTitle(et_title_string);
                mRequest_insert_odd_post.setContent(et_content_string);


                //提交点击时间
                mRequest_insert_odd_post.setReport_time(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));

                //判断. 提示
                if(police_name == null) {
                    ToastUtils.showLong("请扫描民警条码");
                    return;
                }
                if(TextUtils.isEmpty(et_title_string)) {
                    ToastUtils.showLong("请填写标题");
                    return;
                }
                if(mReport_type == null) {
                    ToastUtils.showLong("请选择上报类型");
                    return;
                }
                if(ll_gzlb_and_clbm.getVisibility() == View.VISIBLE && mFalutGenreId == null) {
                    ToastUtils.showLong("请选择故障类别");
                    return;
                }
                if(ll_gzlb_and_clbm.getVisibility() == View.VISIBLE && mNodeDeptName == null) {
                    ToastUtils.showLong("请选择处理部门");
                    return;
                }
                if(TextUtils.isEmpty(et_content_string)) {
                    ToastUtils.showLong("请填写内容");
                    return;
                }

                //TODO 提交
                String commit = gson.toJson(mRequest_insert_odd_post);
                LogUtils.e("零星提交",commit);
                getP().setData(commit,4);
            }
        });

    }

    private void initScan(){
        if(Constance.isNeiMeng) {  //如果是演示                版本则打开相机扫描
            //打开二维码扫描界面
            if(CommonUtil.isCameraCanUse()){
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_POLICE);
            }else{
                Toast.makeText(this,"请打开此应用的摄像头权限！",Toast.LENGTH_SHORT).show();
            }
        }else {
            handleBroadcast = new HandleBroadcast(this, this);
            soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            soundid = soundpool.load("/etc/Scan_new.ogg", 1);
        }
    }

    private void showPromptDlg() {
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setMessage("请扫描民警二维码").show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (resultCode == RESULT_CODE_QR_SCAN && requestCode == REQUEST_CODE_POLICE) {//扫描民警返回
            String scanStr = data.getStringExtra(INTENT_EXTRA_KEY_QR_SCAN);
            boolean status = scanStr.contains("P");
            if (status){
                if(on_Off) {
                    policeCode = scanStr.substring(1);
                    Request_loadPoliceInfo loadPoliceInfo = new Request_loadPoliceInfo();
                    loadPoliceInfo.setCusNumber(mCusnumber);
                    loadPoliceInfo.setPoliceCode(policeCode);
                    getP().setData(gson.toJson(loadPoliceInfo), 10);   //获取民警信息
                    on_Off = false;
                }

            }

        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_odd_post;
    }

    @Override
    public PAddOddPost newP() {
        return new PAddOddPost();
    }

    public void setView(String json, int type) {
        switch (type) {
            case 1: {
//                LogUtils.e(json);

                mEventReportTypeBeanList = gson.fromJson(json,new TypeToken<List<EventReportTypeBean>>(){}.getType());

                for(int i = 0; i < mEventReportTypeBeanList.size();i++) {
                    EventReportTypeBeanStrings.add(mEventReportTypeBeanList.get(i).value);
                }
                mVals =  EventReportTypeBeanStrings.toArray(new String[]{});
//                LogUtils.e(mVals);
                flowlayout_post_type.setAdapter(new TagAdapter<String>(mVals)
                {
                    @Override
                    public View getView(FlowLayout parent, int position, String s)
                    {
                        TextView tv = (TextView) mInflater.inflate(R.layout.tv,
                                flowlayout_post_type, false);
                        tv.setText(s);
                        return tv;
                    }
                });
                flowlayout_post_type.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
                    @Override
                    public void onSelected(Set<Integer> selectPosSet) {
                        LogUtils.e("上报类型",selectPosSet.toString());
                        if(selectPosSet.size() > 0) {
                            index_choose_report_type = selectPosSet.toArray(new Integer[]{})[0];
                            LogUtils.e("上报类型", index_choose_report_type);
                        }
                        //提交上报类型
                        mReport_type = mEventReportTypeBeanList.get(index_choose_report_type).key;
                        mRequest_insert_odd_post.setReport_type(mReport_type);
                        tv_post_type.setText(mEventReportTypeBeanList.get(index_choose_report_type).value);

                        if("故障申报".equals(mEventReportTypeBeanList.get(index_choose_report_type).value)) {
                            //只有选择了故障申报 则显示下方的布局
                            ll_gzlb_and_clbm.setVisibility(View.VISIBLE);

                        }else {
                            ll_gzlb_and_clbm.setVisibility(View.GONE);
//                            mRequest_insert_odd_post.setFalut_genre_id("0");
//                            mRequest_insert_odd_post.setFalut_genre_name("");
//                            mRequest_insert_odd_post.setHandle_dept_id("0");
//                            mRequest_insert_odd_post.setHandle_dept_name("");

                        }

                    }
                });

                et_post_type.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                DialogUIUtils.showBottomSheetAndCancel(getApplicationContext(), EventReportTypeBeanStrings, "取消", new DialogUIItemListener() {
                                    @Override
                                    public void onItemClick(CharSequence text, int position) {
                                        //点击条目后
                                        LogUtils.e("上报类型",mEventReportTypeBeanList.get(position).value);
                                        mReport_type = mEventReportTypeBeanList.get(position).key;
                                        mRequest_insert_odd_post.setReport_type(mReport_type);
                                        if("故障申报".equals(mEventReportTypeBeanList.get(position).value)) {
                                            //只有选择了故障申报 则显示下方的布局
                                            ll_gzlb_and_clbm.setVisibility(View.VISIBLE);

                                        }else {
                                            ll_gzlb_and_clbm.setVisibility(View.GONE);
//                            mRequest_insert_odd_post.setFalut_genre_id("0");
//                            mRequest_insert_odd_post.setFalut_genre_name("");
//                            mRequest_insert_odd_post.setHandle_dept_id("0");
//                            mRequest_insert_odd_post.setHandle_dept_name("");

                                        }
                                        et_post_type.setText(mEventReportTypeBeanList.get(position).value);

                                    }
                                }).show();
                                break;
                        }

                        return true;
                    }
                });

            }
            break;
            case 2: {
                LogUtils.e("故障类别",json);
                mEventLoadFaultCategories =  gson.fromJson(json,new TypeToken<List<EventLoadFaultCategory>>(){}.getType());
                for(int i = 0; i < mEventLoadFaultCategories.size();i++) {
                    loadFaultCategorys.add(mEventLoadFaultCategories.get(i).name);
                }
                mVals2 =  loadFaultCategorys.toArray(new String[]{});
                flowlayout_guzhang_leibie.setAdapter(new TagAdapter<String>(mVals2)
                {
                    @Override
                    public View getView(FlowLayout parent, int position, String s)
                    {
                        TextView tv = (TextView) mInflater.inflate(R.layout.tv,
                                flowlayout_post_type, false);
                        tv.setText(s);
                        return tv;
                    }
                });
                flowlayout_guzhang_leibie.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
                    @Override
                    public void onSelected(Set<Integer> selectPosSet) {
                        LogUtils.e("故障类别",selectPosSet.toString());
                        if(selectPosSet.size() > 0) {
                            index_choose_guzhang_leibie = selectPosSet.toArray(new Integer[]{})[0];
                            LogUtils.e("故障类别", index_choose_guzhang_leibie);
                        }
                        tv_guzhang_leibie.setText(mEventLoadFaultCategories.get(index_choose_guzhang_leibie).name);
                        //提交故障类别ID和名称
                        mFalutGenreId = mEventLoadFaultCategories.get(index_choose_guzhang_leibie).id;
                        mRequest_insert_odd_post.setFalut_genre_id(mFalutGenreId);
                        mRequest_insert_odd_post.setFalut_genre_name(mEventLoadFaultCategories.get(index_choose_guzhang_leibie).name);


                    }
                });

            }
            break;
            case 3 : {
                LogUtils.e(json);
                mDatas = gson.fromJson(json,new TypeToken<List<FileBean>>(){}.getType());
                try {
                    mAdapter = new SimpleTreeAdapter<FileBean>(mTree, this, mDatas,10);

                    mAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                        @Override
                        public void onClick(Node node, int position) {
                            if (node.isLeaf()) {

                                //得到的node.getName()能正确取出名字,  则循环取出id
                                for(int i = 0; i < mDatas.size(); i++) {
                                    FileBean fileBean = mDatas.get(i);
                                    mNodeDeptName = node.getName();
                                    if(mNodeDeptName.equals(fileBean.getDept_name())) {
                                        String dept_id = fileBean.getDept_id() + "";
                                        mRequest_insert_odd_post.setHandle_dept_id(dept_id);
                                        mRequest_insert_odd_post.setHandle_dept_name(mNodeDeptName);
                                        tv_chuli_bumen.setText(mNodeDeptName);
                                    }
                                }
                            }
                        }

                    });

                    //手动设置ListView高度
                    if(mTree == null) return;
//                    ListAdapter listAdapter = mTree.getAdapter();
                    if (mAdapter == null) {
                        // pre-condition
                        return;
                    }
                    int totalHeight = 0;
                    for (int i = 0; i < mAdapter.getCount(); i++) {
                        View listItem = mAdapter.getView(i, null, mTree);
                        listItem.measure(0, 0);
                        totalHeight += listItem.getMeasuredHeight();
                    }
                    mParams = mTree.getLayoutParams();
                    mParams.height = totalHeight + (mTree.getDividerHeight() * (mAdapter.getCount() - 1));
                    mTree.setLayoutParams(mParams);
                    mTree.setAdapter(mAdapter);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
            break;
            case 4 :{
                ToastUtils.showLong("提交成功");
                finish();
            }
            break;
            case 10 : {   //获取民警信息


//                loadingDialog.dismiss();
                JSONObject json2 = null;
                try {
                    json2 = new JSONObject(json);
                    police_name=  json2.getString("police_name");
                    police_id= json2.getString("police_id");
                    department_id= json2.getString("department_id");
                    department_name= json2.getString("department_name");
                    tv_policeName.setText(police_name);
                    tv_policeID.setText(policeCode);

                    //提交上报民警id和部门
                    mRequest_insert_odd_post.setReport_police_id(police_id);
                    mRequest_insert_odd_post.setReport_police_name(police_name);
                    //提交上报部门ID和名称
                    mRequest_insert_odd_post.setReport_dept_id(department_id);
                    mRequest_insert_odd_post.setReport_dept_name(department_name);
                } catch (JSONException e) {

                }

            }
            break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (handleBroadcast != null) {
//            handleBroadcast.overBroadcastReceiver(this);
//        }

    }
}
